package com.jabo.wechatmomentsdemo.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.Spannable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.jabo.wechatmomentsdemo.R;

import java.util.ArrayList;
import java.util.List;

/**
 * @anthor JZheng3
 * @Time: 2020/9/6
 */
public class CommentsLinearLayout extends LinearLayout {

    private List<TextView> mTextViews;
    private int mTextSize;
    private int mTextColor;

    public CommentsLinearLayout(Context context) {
        this(context, null);
    }

    public CommentsLinearLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CommentsLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttrs(context, attrs);
        init();
    }

    private void init() {
        setOrientation(VERTICAL);
        mTextViews = new ArrayList<>();
    }

    private void initAttrs(Context context, AttributeSet attributeSet) {
        TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.CommentsLinearLayoutView);
        mTextSize = (int) typedArray.getDimension(R.styleable.CommentsLinearLayoutView_textSize, getResources().getDimensionPixelSize(R.dimen.sp_10));//单图的时候高度
        mTextColor = (int) typedArray.getDimension(R.styleable.CommentsLinearLayoutView_textColor, Color.BLACK);//单图的时候高度
        typedArray.recycle();
    }

    private void createTextView() {
        TextView textView = new TextView(getContext());
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
        textView.setTextColor(mTextColor);
        mTextViews.add(textView);
        addView(textView);
    }

    public void setDatas(List<Spannable> strings) {
        reLayout(strings);
    }


    private void reLayout(List<Spannable> strings) {
        if (strings == null || strings.isEmpty()) {
            setVisibility(GONE);
            return;
        }
        setVisibility(VISIBLE);
        int size = mTextViews.size();
        int size1 = strings.size();
        if (size1 <= size) {
            for (int i = 0; i < size; i++) {
                TextView textView = mTextViews.get(i);
                if (i < size1) {
                    textView.setText(strings.get(i));
                } else {
                    mTextViews.remove(textView);
                    removeView(textView);
                }
            }
        } else {
            for (int i = 0; i < size1; i++) {
                if (i >= size) {
                    createTextView();
                }
                TextView textView = mTextViews.get(i);
                textView.setText(strings.get(i));
            }
        }
    }
}
